'use client';

import { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import * as Cesium from 'cesium';
import { Viewer, CesiumComponentRef } from 'resium';
import { TrajectoryPoint, TrajectoryViewerProps } from './types';

// 引入Cesium资源文件
import "cesium/Build/Cesium/Widgets/widgets.css";

// 地图容器样式
const CesiumContainer = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #061730;
  
  .cesium-viewer {
    width: 100%;
    height: 100%;
  }
  
  .cesium-viewer-bottom {
    display: none;
  }

  .cesium-widget-credits {
    display: none !important;
  }
  
  .cesium-widget,
  .cesium-widget canvas {
    width: 100% !important;
    height: 100% !important;
  }
`;

// 时间轴控制器样式
const TimelineControl = styled.div`
  position: absolute;
  bottom: 20px;
  left: 20px;
  right: 20px;
  background-color: rgba(0, 21, 41, 0.7);
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  z-index: 10;
`;

// 时间轴进度条容器
const TimelineSliderContainer = styled.div`
  width: 100%;
  position: relative;
  margin: 10px 0;
  padding: 0 10px;
`;

// 时间轴进度条
const TimelineSlider = styled.input`
  width: 100%;
  -webkit-appearance: none;
  height: 6px;
  background: rgba(24, 144, 255, 0.2);
  outline: none;
  border-radius: 3px;
  
  &::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background: #1890ff;
    cursor: pointer;
    border: 2px solid white;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  }
`;

// 时间轴时间标签
const TimeLabel = styled.div`
  position: absolute;
  bottom: 15px;
  font-size: 11px;
  color: white;
  transform: translateX(-50%);
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
`;

// 当前时间轴时间标签
const CurrentTimeLabel = styled.div`
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(24, 144, 255, 0.8);
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  white-space: nowrap;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
  pointer-events: none;
  transition: left 0.1s ease;
`;

// 控制按钮容器
const ControlButtons = styled.div`
  display: flex;
  gap: 10px;
  justify-content: center;
`;

// 控制按钮
const ControlButton = styled.button`
  padding: 5px 10px;
  background-color: rgba(24, 144, 255, 0.3);
  color: white;
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.5);
  }
  
  &:active {
    background-color: rgba(24, 144, 255, 0.7);
  }
`;

// 轨迹信息面板
const TrajectoryInfo = styled.div`
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: rgba(0, 21, 41, 0.7);
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  padding: 10px;
  color: white;
  font-size: 12px;
  z-index: 10;
  min-width: 200px;
`;

// 信息项
const InfoItem = styled.div`
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  
  &:last-child {
    margin-bottom: 0;
  }
`;

// 标签
const InfoLabel = styled.span`
  color: #a0cfff;
  margin-right: 10px;
`;

// 值
const InfoValue = styled.span`
  color: white;
  font-weight: 500;
`;

// 地图工具栏
const MapToolbar = styled.div`
  position: absolute;
  top: 20px;
  left: 20px;
  background-color: rgba(0, 21, 41, 0.7);
  border: 1px solid rgba(24, 144, 255, 0.5);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px;
  gap: 8px;
  z-index: 10;
`;

// 地图工具按钮
const ToolButton = styled.button`
  width: 34px;
  height: 34px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(24, 144, 255, 0.3);
  color: white;
  border: 1px solid rgba(24, 144, 255, 0.7);
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: rgba(24, 144, 255, 0.5);
    transform: translateY(-2px);
  }
  
  &:active {
    transform: translateY(0);
    background-color: rgba(24, 144, 255, 0.7);
  }
  
  &.active {
    background-color: rgba(24, 144, 255, 0.7);
    box-shadow: 0 0 5px #1890ff;
  }
`;

// 加载遮罩
const LoadingOverlay = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 21, 41, 0.7);
  color: white;
  font-size: 18px;
  z-index: 100;
`;

// 测量结果面板
const MeasurePanel = styled.div`
  position: absolute;
  left: 20px;
  bottom: 120px;
  background-color: rgba(0, 21, 41, 0.8);
  border: 1px solid rgba(24, 144, 255, 0.7);
  border-radius: 4px;
  padding: 10px;
  color: white;
  font-size: 14px;
  z-index: 20;
  min-width: 180px;
  display: flex;
  flex-direction: column;
  gap: 5px;
`;

// 测量提示
const MeasureHint = styled.div`
  position: absolute;
  left: 50%;
  top: 10px;
  transform: translateX(-50%);
  background-color: rgba(0, 21, 41, 0.7);
  color: #00ffff;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 20;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
`;

export default function TrajectoryViewer({ 
  trajectoryData, 
  droneId, 
  sensorId,
  date,
  isLoading 
}: TrajectoryViewerProps & { isLoading?: boolean }) {
  const viewerRef = useRef<CesiumComponentRef<Cesium.Viewer>>(null);
  const [currentPointIndex, setCurrentPointIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState(1);
  const [timelineMax, setTimelineMax] = useState(100);
  const [viewerInitialized, setViewerInitialized] = useState(false);
  const trajectoryPointsRef = useRef<TrajectoryPoint[]>([]);
  const droneEntityRef = useRef<Cesium.Entity | null>(null);
  const pathEntityRef = useRef<Cesium.Entity | null>(null);
  const playbackIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const timelineSliderRef = useRef<HTMLInputElement>(null);
  
  // 添加地形和注记图层状态
  const [terrainEnabled, setTerrainEnabled] = useState(false);
  const [terrainLoading, setTerrainLoading] = useState(false);
  const [annotationVisible, setAnnotationVisible] = useState(true);
  const annotationLayerRef = useRef<Cesium.ImageryLayer | null>(null);
  
  // 添加距离测量工具状态
  const [measuringDistance, setMeasuringDistance] = useState(false);
  const [measureResult, setMeasureResult] = useState<string | null>(null);
  const measurePointsRef = useRef<Cesium.Entity[]>([]);
  const measureLineRef = useRef<Cesium.Entity | null>(null);
  const measureHandlerRef = useRef<Cesium.ScreenSpaceEventHandler | null>(null);
  
  // 添加时间信息状态
  const [startTimeLabel, setStartTimeLabel] = useState<string>('');
  const [endTimeLabel, setEndTimeLabel] = useState<string>('');
  const [currentTimeLeft, setCurrentTimeLeft] = useState<number>(50);
  
  // 中科星图注记图层URL
  const GEOVIS_ANNO_URL = 'https://www.supermapol.com/proxy/g2yw6g0o/iserver/services/map-geovis-cia/rest/maps/GEOVIS_Cia/zxyTileImage.png?x={x}&y={y}&z={z}';
  
  // 格式化时间字符串 (HH:MM:SS)
  const formatTimeStr = (timeStr: string) => {
    try {
      const date = new Date(timeStr);
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    } catch (e) {
      console.error('格式化时间出错:', e);
      return timeStr;
    }
  };
  
  console.log('TrajectoryViewer接收到的props:', { trajectoryData, droneId, sensorId, date, isLoading });
  
  // 简化的初始化Cesium查看器函数
  const initializeCesium = () => {
    try {
      if (!viewerRef.current?.cesiumElement) return false;
      
      console.log('开始初始化Cesium查看器');
      const viewer = viewerRef.current.cesiumElement;
      
      // 设置Cesium Ion令牌 - 确保在使用任何功能前设置
      Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmZmZkZWNlZC0zMGFlLTRkNjEtODczNS0wM2UwNzIzZTgzOWQiLCJpZCI6Mjg5NDY0LCJpYXQiOjE3NDY1NzQ0MjJ9.AqUCB4gsgFQcN4lW-vmsosO3wcGLSTTiHNLGq4GRrQg';
      const AMAP_URL = 'https://www.supermapol.com/proxy/y8f150ad/iserver/services/map-geovis-img/rest/maps/GEOVIS_Img/zxyTileImage.png?x={x}&y={y}&z={z}';

      // 配置Cesium查看器
      viewer.scene.globe.enableLighting = false;
      viewer.scene.globe.depthTestAgainstTerrain = false;
      
      // 禁用不需要的UI组件
      if (viewer.animation) (viewer.animation.container as HTMLElement).style.visibility = 'hidden';
      if (viewer.timeline) (viewer.timeline.container as HTMLElement).style.visibility = 'hidden';
      if (viewer.fullscreenButton) (viewer.fullscreenButton.container as HTMLElement).style.visibility = 'hidden';
      if (viewer.baseLayerPicker) (viewer.baseLayerPicker.container as HTMLElement).style.visibility = 'hidden';
      
      // 使用更简单的影像提供者
      viewer.imageryLayers.removeAll();
      
      // 添加底图
      viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
          url: AMAP_URL,
          minimumLevel: 1,
          maximumLevel: 18
        })
      );
      
      // 添加注记图层
      const annotationProvider = new Cesium.UrlTemplateImageryProvider({
        url: GEOVIS_ANNO_URL,
        minimumLevel: 1,
        maximumLevel: 18
      });
      
      annotationLayerRef.current = viewer.imageryLayers.addImageryProvider(annotationProvider);
      
      // 设置初始状态
      if (annotationLayerRef.current) {
        annotationLayerRef.current.show = annotationVisible;
      }
      
      console.log('Cesium查看器初始化完成');
      return true;
    } catch (error) {
      console.error('[DEBUG] 初始化Cesium时发生错误:', error);
      return false;
    }
  };
  
  // 初始化Cesium查看器 - 使用更简单的方法
  useEffect(() => {
    console.log('[DEBUG] 组件挂载，准备初始化Cesium');
    let isInitialized = false;
    
    // 等待DOM完全加载和渲染
    const initTimer = setTimeout(() => {
      console.log('[DEBUG] 延时结束，检查viewerRef:', Boolean(viewerRef.current?.cesiumElement));
      if (viewerRef.current?.cesiumElement && !viewerInitialized) {
        console.log('[DEBUG] 尝试初始化Cesium...');
        try {
          isInitialized = initializeCesium();
          if (isInitialized) {
            console.log('[DEBUG] Cesium初始化成功，设置viewerInitialized为true');
            setViewerInitialized(true);
          } else {
            console.log('[DEBUG] Cesium初始化失败');
          }
        } catch (e) {
          console.error('[DEBUG] 初始化过程中出错:', e);
        }
      } else {
        console.log('[DEBUG] viewerRef或viewerInitialized条件不满足，跳过初始化');
      }
    }, 1000); // 增加延时，确保DOM完全加载
    
    // 清理函数
    return () => {
      console.log('[DEBUG] 组件卸载，清理资源');
      clearTimeout(initTimer);
      if (viewerRef.current?.cesiumElement) {
        try {
          viewerRef.current.cesiumElement.entities.removeAll();
        } catch (e) {
          console.error('[DEBUG] 清理Cesium实体时出错:', e);
        }
        setViewerInitialized(false);
      }
    };
  }, []); // 仅在组件挂载时运行一次
  
  // 处理轨迹数据
  useEffect(() => {
    if (!trajectoryData || !droneId || !sensorId || !date || !viewerInitialized) {
      console.log('[DEBUG] 数据条件不满足，跳过轨迹处理', { 
        hasTrajectoryData: Boolean(trajectoryData), 
        droneId,
        sensorId,
        date, 
        viewerInitialized 
      });
      return;
    }
    
    if (!viewerRef.current?.cesiumElement) {
      console.log('[DEBUG] viewerRef.current为空，跳过轨迹处理');
      return;
    }
    
    const viewer = viewerRef.current.cesiumElement;
    
    // 清除之前的实体
    try {
      console.log('[DEBUG] 清除之前的实体');
      if (droneEntityRef.current) {
        viewer.entities.remove(droneEntityRef.current);
        droneEntityRef.current = null;
      }
      if (pathEntityRef.current) {
        viewer.entities.remove(pathEntityRef.current);
        pathEntityRef.current = null;
      }
    } catch (error) {
      console.error('[DEBUG] 清除实体时出错:', error);
    }
    
    // 检查轨迹数据是否存在
    const combinedId = `${droneId}_${sensorId}`;
    console.log('[DEBUG] 检查轨迹数据', { combinedId, date });
    
    if (!trajectoryData[combinedId] || !trajectoryData[combinedId].dates || !trajectoryData[combinedId].dates[date]) {
      console.log('[DEBUG] 未找到轨迹数据', trajectoryData);
      return;
    }
    
    // 获取轨迹点
    const trajectoryPoints = trajectoryData[combinedId].dates[date];
    trajectoryPointsRef.current = trajectoryPoints;
    
    console.log('[DEBUG] 获取到轨迹点数量:', trajectoryPoints.length);
    if (trajectoryPoints.length === 0) {
      console.log('[DEBUG] 轨迹点为空，跳过处理');
      return;
    }
    
    // 设置时间轴最大值
    setTimelineMax(trajectoryPoints.length - 1);
    
    // 设置起点和终点时间标签
    if (trajectoryPoints.length > 0) {
      const firstPoint = trajectoryPoints[0];
      const lastPoint = trajectoryPoints[trajectoryPoints.length - 1];
      
      setStartTimeLabel(formatTimeStr(firstPoint.created_at));
      setEndTimeLabel(formatTimeStr(lastPoint.created_at));
    }
    
    try {
      // 创建位置数据
      console.log('[DEBUG] 创建位置数据');
      const positions: Cesium.Cartesian3[] = trajectoryPoints.map(point => 
        Cesium.Cartesian3.fromDegrees(
          point.drone_gps_lng, 
          point.drone_gps_lat, 
          point.drone_height
        )
      );
      
      // 添加轨迹路径
      console.log('[DEBUG] 添加轨迹路径');
      pathEntityRef.current = viewer.entities.add({
        polyline: {
          positions: positions,
          width: 3,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.2,
            color: Cesium.Color.CYAN
          })
        }
      });
      
      // 添加无人机实体
      console.log('[DEBUG] 添加无人机实体');
      const firstPoint = trajectoryPoints[0];
      droneEntityRef.current = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(
          firstPoint.drone_gps_lng, 
          firstPoint.drone_gps_lat, 
          firstPoint.drone_height
        ),
        point: {
          pixelSize: 10,
          color: Cesium.Color.RED,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2
        },
        label: {
          text: '无人机',
          font: '14px sans-serif',
          fillColor: Cesium.Color.WHITE,
          outlineColor: Cesium.Color.BLACK,
          outlineWidth: 2,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          pixelOffset: new Cesium.Cartesian2(0, -20)
        }
      });
      
      // 将视图缩放到无人机位置
      console.log('[DEBUG] 将视图缩放到无人机位置');
      viewer.flyTo(droneEntityRef.current, {
        duration: 2,
        offset: new Cesium.HeadingPitchRange(
          0,
          Cesium.Math.toRadians(-45),
          500
        )
      });
    } catch (error) {
      console.error('[DEBUG] 处理轨迹数据时出错:', error);
    }
  }, [trajectoryData, droneId, sensorId, date, viewerInitialized]);
  
  // 清理定时器
  useEffect(() => {
    return () => {
      if (playbackIntervalRef.current) {
        clearInterval(playbackIntervalRef.current);
        playbackIntervalRef.current = null;
      }
      
      // 清理测量相关资源
      if (measureHandlerRef.current) {
        measureHandlerRef.current.destroy();
        measureHandlerRef.current = null;
      }
      clearMeasurement();
    };
  }, []);
  
  // 在组件中添加以下代码来检查viewerRef
  useEffect(() => {
    console.log('viewerRef状态:', {
      current: viewerRef.current,
      cesiumElement: viewerRef.current?.cesiumElement
    });
  }, [viewerRef.current]);
  
  // 处理时间轴滑动
  const handleTimelineChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const index = parseInt(e.target.value);
    setCurrentPointIndex(index);
    updateDronePosition(index);
    
    // 更新当前时间标签位置
    // 计算当前值在滑动条中的相对位置(百分比)
    const percentage = (index / timelineMax) * 100;
    setCurrentTimeLeft(percentage);
  };
  
  // 更新无人机位置
  const updateDronePosition = (index: number) => {
    if (!viewerRef.current?.cesiumElement || !droneEntityRef.current || trajectoryPointsRef.current.length === 0) return;
    
    const point = trajectoryPointsRef.current[index];
    const position = Cesium.Cartesian3.fromDegrees(
      point.drone_gps_lng,
      point.drone_gps_lat,
      point.drone_height
    );
    
    droneEntityRef.current.position = new Cesium.ConstantPositionProperty(position);
  };
  
  // 播放/暂停轨迹
  const togglePlayback = () => {
    if (isPlaying) {
      // 停止播放
      if (playbackIntervalRef.current) {
        clearInterval(playbackIntervalRef.current);
        playbackIntervalRef.current = null;
      }
    } else {
      // 开始播放
      playbackIntervalRef.current = setInterval(() => {
        setCurrentPointIndex(prev => {
          // 达到末尾，停止播放
          if (prev >= trajectoryPointsRef.current.length - 1) {
            setIsPlaying(false);
            if (playbackIntervalRef.current) {
              clearInterval(playbackIntervalRef.current);
              playbackIntervalRef.current = null;
            }
            return prev;
          }
          
          const nextIndex = prev + 1;
          updateDronePosition(nextIndex);
          return nextIndex;
        });
      }, 1000 / playbackSpeed);
    }
    
    setIsPlaying(!isPlaying);
  };
  
  // 重置轨迹
  const resetPlayback = () => {
    setCurrentPointIndex(0);
    updateDronePosition(0);
    setIsPlaying(false);
    if (playbackIntervalRef.current) {
      clearInterval(playbackIntervalRef.current);
      playbackIntervalRef.current = null;
    }
  };
  
  // 切换播放速度
  const toggleSpeed = () => {
    // 循环切换速度: 1x -> 2x -> 4x -> 1x
    const newSpeed = playbackSpeed === 1 ? 2 : playbackSpeed === 2 ? 4 : 1;
    setPlaybackSpeed(newSpeed);
    
    // 如果正在播放，更新播放间隔
    if (isPlaying && playbackIntervalRef.current) {
      clearInterval(playbackIntervalRef.current);
      playbackIntervalRef.current = setInterval(() => {
        setCurrentPointIndex(prev => {
          if (prev >= trajectoryPointsRef.current.length - 1) {
            setIsPlaying(false);
            if (playbackIntervalRef.current) {
              clearInterval(playbackIntervalRef.current);
              playbackIntervalRef.current = null;
            }
            return prev;
          }
          
          const nextIndex = prev + 1;
          updateDronePosition(nextIndex);
          return nextIndex;
        });
      }, 1000 / newSpeed);
    }
  };
  
  // 跟随无人机视角
  const followDrone = () => {
    if (!viewerRef.current?.cesiumElement || !droneEntityRef.current || trajectoryPointsRef.current.length === 0) return;
    
    const viewer = viewerRef.current.cesiumElement;
    const point = trajectoryPointsRef.current[currentPointIndex];
    
    // 计算位置和视角
    const dronePosition = Cesium.Cartesian3.fromDegrees(
      point.drone_gps_lng,
      point.drone_gps_lat,
      point.drone_height + 50 // 稍微高于无人机
    );
    
    // 查看器飞行到指定位置
    viewer.camera.flyTo({
      destination: dronePosition,
      orientation: {
        heading: Cesium.Math.toRadians(0), // 视角朝北
        pitch: Cesium.Math.toRadians(-30), // 视角俯视
        roll: 0
      },
      duration: 1
    });
  };
  
  // 获取当前点的详细信息
  const getCurrentPointInfo = () => {
    if (trajectoryPointsRef.current.length === 0) return null;
    return trajectoryPointsRef.current[currentPointIndex];
  };
  
  // 切换三维地形
  const toggleTerrain = async () => {
    if (!viewerRef.current?.cesiumElement) return;
    
    const viewer = viewerRef.current.cesiumElement;
    
    if (terrainEnabled) {
      // 禁用地形
      setTerrainLoading(true);
      try {
        viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider();
        setTerrainEnabled(false);
      } catch (error) {
        console.error('[DEBUG] 禁用地形时出错:', error);
      } finally {
        setTerrainLoading(false);
      }
    } else {
      // 启用地形
      setTerrainLoading(true);
      try {
        const terrain = await Cesium.createWorldTerrainAsync();
        viewer.terrainProvider = terrain;
        setTerrainEnabled(true);
      } catch (error) {
        console.error('[DEBUG] 启用地形时出错:', error);
      } finally {
        setTerrainLoading(false);
      }
    }
  };
  
  // 切换注记图层
  const toggleAnnotation = () => {
    if (!annotationLayerRef.current) return;
    
    const newVisibility = !annotationVisible;
    annotationLayerRef.current.show = newVisibility;
    setAnnotationVisible(newVisibility);
  };
  
  // 开始距离测量
  const startMeasureDistance = () => {
    if (!viewerRef.current?.cesiumElement) return;
    
    const viewer = viewerRef.current.cesiumElement;
    setMeasuringDistance(true);
    setMeasureResult(null);
    
    // 清除之前的测量结果
    clearMeasurement();
    
    // 创建新的事件处理器
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    measureHandlerRef.current = handler;
    
    // 第一个点
    let firstPosition: Cesium.Cartesian3 | null = null;
    
    // 监听左键点击事件，添加测量点
    handler.setInputAction((click: Cesium.ScreenSpaceEventHandler.PositionedEvent) => {
      try {
        const cartesian = viewer.scene.pickPosition(click.position);
        if (!cartesian) return;
        
        // 如果是第一个点
        if (!firstPosition) {
          firstPosition = cartesian;
          
          // 添加第一个点标记
          const pointEntity = viewer.entities.add({
            position: cartesian,
            point: {
              pixelSize: 8,
              color: Cesium.Color.RED,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            },
            label: {
              text: '起点',
              font: '14px sans-serif',
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              pixelOffset: new Cesium.Cartesian2(0, -20),
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
          });
          
          measurePointsRef.current.push(pointEntity);
        } else {
          // 添加第二个点标记
          const pointEntity = viewer.entities.add({
            position: cartesian,
            point: {
              pixelSize: 8,
              color: Cesium.Color.BLUE,
              outlineColor: Cesium.Color.WHITE,
              outlineWidth: 2,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            },
            label: {
              text: '终点',
              font: '14px sans-serif',
              fillColor: Cesium.Color.WHITE,
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              pixelOffset: new Cesium.Cartesian2(0, -20),
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
          });
          
          measurePointsRef.current.push(pointEntity);
          
          // 添加连接线
          measureLineRef.current = viewer.entities.add({
            polyline: {
              positions: [firstPosition, cartesian],
              width: 3,
              material: new Cesium.PolylineDashMaterialProperty({
                color: Cesium.Color.YELLOW,
                dashLength: 16.0
              }),
              clampToGround: true
            }
          });
          
          // 计算距离
          const cartographicFirst = Cesium.Cartographic.fromCartesian(firstPosition);
          const cartographicSecond = Cesium.Cartographic.fromCartesian(cartesian);
          
          const startLon = Cesium.Math.toDegrees(cartographicFirst.longitude);
          const startLat = Cesium.Math.toDegrees(cartographicFirst.latitude);
          const endLon = Cesium.Math.toDegrees(cartographicSecond.longitude);
          const endLat = Cesium.Math.toDegrees(cartographicSecond.latitude);
          
          // 使用Haversine公式计算距离
          const distance = calculateDistance(startLat, startLon, endLat, endLon);
          
          // 显示结果
          setMeasureResult(`距离: ${distance.toFixed(2)} 米`);
          
          // 清除事件处理器，结束测量
          if (measureHandlerRef.current) {
            measureHandlerRef.current.destroy();
            measureHandlerRef.current = null;
          }
        }
      } catch (error) {
        console.error('[DEBUG] 处理测量点击时出错:', error);
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
    // 监听右键点击事件，取消测量
    handler.setInputAction(() => {
      cancelMeasurement();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  };
  
  // 计算两点间的距离 (Haversine公式)
  const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
    const R = 6371000; // 地球半径，单位米
    const dLat = Cesium.Math.toRadians(lat2 - lat1);
    const dLon = Cesium.Math.toRadians(lon2 - lon1);
    
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(Cesium.Math.toRadians(lat1)) * Math.cos(Cesium.Math.toRadians(lat2)) * 
      Math.sin(dLon/2) * Math.sin(dLon/2);
    
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const distance = R * c;
    
    return distance;
  };
  
  // 清除测量结果
  const clearMeasurement = () => {
    if (!viewerRef.current?.cesiumElement) return;
    
    const viewer = viewerRef.current.cesiumElement;
    
    // 移除点标记
    measurePointsRef.current.forEach(entity => {
      if (entity && viewer.entities.contains(entity)) {
        viewer.entities.remove(entity);
      }
    });
    measurePointsRef.current = [];
    
    // 移除连接线
    if (measureLineRef.current && viewer.entities.contains(measureLineRef.current)) {
      viewer.entities.remove(measureLineRef.current);
      measureLineRef.current = null;
    }
    
    setMeasureResult(null);
  };
  
  // 取消测量
  const cancelMeasurement = () => {
    // 清除测量实体
    clearMeasurement();
    
    // 销毁事件处理器
    if (measureHandlerRef.current) {
      measureHandlerRef.current.destroy();
      measureHandlerRef.current = null;
    }
    
    setMeasuringDistance(false);
  };
  
  const currentPoint = getCurrentPointInfo();
  
  // 如果正在加载或无数据，显示加载状态
  if (isLoading || !trajectoryData || !droneId || !sensorId || !date) {
    return (
      <CesiumContainer>
        <div className="w-full h-full flex items-center justify-center">
          <div className="text-blue-300">
            {isLoading ? '加载轨迹数据中...' : '请选择有效的无人机和日期'}
          </div>
        </div>
      </CesiumContainer>
    );
  }
  
  return (
    <CesiumContainer>
      <Viewer
        ref={viewerRef}
        full
        homeButton={false}
        geocoder={false}
        sceneModePicker={false}
        navigationHelpButton={false}
        animation={false}
        timeline={false}
        infoBox={false}
        selectionIndicator={false}
      />
      
      {terrainLoading && (
        <LoadingOverlay>
          {terrainEnabled ? '正在禁用三维地形...' : '正在加载三维地形...'}
        </LoadingOverlay>
      )}
      
      {/* 地图工具栏 */}
      <MapToolbar>
        <ToolButton 
          onClick={toggleTerrain} 
          title={terrainEnabled ? "禁用三维地形" : "启用三维地形"}
          className={terrainEnabled ? 'active' : ''}
          disabled={terrainLoading}
        >
          🌋
        </ToolButton>
        <ToolButton 
          onClick={toggleAnnotation} 
          title={annotationVisible ? "隐藏路网" : "显示路网"}
          className={annotationVisible ? 'active' : ''}
        >
          🛣️
        </ToolButton>
        <ToolButton 
          onClick={measuringDistance ? cancelMeasurement : startMeasureDistance}
          title={measuringDistance ? "取消测距" : "开始测距"} 
          className={measuringDistance ? 'active' : ''}
        >
          📏
        </ToolButton>
      </MapToolbar>
      
      {/* 测量提示 */}
      {measuringDistance && !measureResult && (
        <MeasureHint>
          点击地图添加起点，再次点击添加终点测量距离，右键点击取消
        </MeasureHint>
      )}
      
      {/* 测量结果面板 */}
      {measureResult && (
        <MeasurePanel>
          <div style={{ marginBottom: '5px', color: '#1890ff', fontWeight: 'bold' }}>
            测量结果
          </div>
          <div>{measureResult}</div>
          <ControlButton 
            onClick={cancelMeasurement}
            style={{ marginTop: '5px', alignSelf: 'flex-end', padding: '3px 8px', fontSize: '12px' }}
          >
            清除
          </ControlButton>
        </MeasurePanel>
      )}
      
      {trajectoryPointsRef.current.length > 0 && (
        <>
          <TimelineControl>
            <TimelineSliderContainer>
              <TimelineSlider
                ref={timelineSliderRef}
                type="range"
                min={0}
                max={timelineMax}
                value={currentPointIndex}
                onChange={handleTimelineChange}
              />
              {/* 起点时间 */}
              <TimeLabel style={{ left: '2%' }}>
                {startTimeLabel}
              </TimeLabel>
              
              {/* 终点时间 */}
              <TimeLabel style={{ left: '98%' }}>
                {endTimeLabel}
              </TimeLabel>
              
              {/* 位置指示器 */}
              <TimeLabel style={{ left: '50%' }}>
                {currentPointIndex + 1} / {trajectoryPointsRef.current.length}
              </TimeLabel>
            </TimelineSliderContainer>
            
            {/* 当前时间浮动显示 */}
            <CurrentTimeLabel style={{ left: `${currentTimeLeft}%` }}>
              {currentPoint ? formatTimeStr(currentPoint.created_at) : '未知'}
            </CurrentTimeLabel>
            
            <ControlButtons>
              <ControlButton onClick={resetPlayback}>
                重置
              </ControlButton>
              <ControlButton onClick={togglePlayback}>
                {isPlaying ? '暂停' : '播放'}
              </ControlButton>
              <ControlButton onClick={toggleSpeed}>
                {playbackSpeed}x 速度
              </ControlButton>
              <ControlButton onClick={followDrone}>
                跟随视角
              </ControlButton>
            </ControlButtons>
          </TimelineControl>
          
          <TrajectoryInfo>
            <InfoItem>
              <InfoLabel>无人机型号:</InfoLabel>
              <InfoValue>{currentPoint?.model || '未知'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>经度:</InfoLabel>
              <InfoValue>{currentPoint?.drone_gps_lng || '未知'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>纬度:</InfoLabel>
              <InfoValue>{currentPoint?.drone_gps_lat || '未知'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>高度:</InfoLabel>
              <InfoValue>{currentPoint?.drone_height || 0} 米</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>距离:</InfoLabel>
              <InfoValue>{currentPoint?.drone_distance || 0} 米</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>时间:</InfoLabel>
              <InfoValue>{currentPoint?.created_at || '未知'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>传感器ID:</InfoLabel>
              <InfoValue>{currentPoint?.sensor_id || '未知'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>地形:</InfoLabel>
              <InfoValue>{terrainEnabled ? '已启用' : '已禁用'}</InfoValue>
            </InfoItem>
            <InfoItem>
              <InfoLabel>路网:</InfoLabel>
              <InfoValue>{annotationVisible ? '已显示' : '已隐藏'}</InfoValue>
            </InfoItem>
          </TrajectoryInfo>
        </>
      )}
    </CesiumContainer>
  );
} 